// Copyright DustedPixels.com 2008. All rights reserved.

package com.dustedpixels.jasmin.unit.compiler;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;

import org.apache.commons.io.IOUtils;

/**
 * @author micapolos@gmail.com (Michal Pociecha-Los)
 */
public final class UnitToProcessConverter {
  public static String convert(String unitCode) {
    try {
      Writer writer = new StringWriter();
      BufferedReader reader = new BufferedReader(new StringReader(unitCode));
      String line;
      MatchResult methodMatchResult = null;
      String methodIndent = null;
      do {
        line = reader.readLine();
        if (line != null) {
          line = line.replaceFirst("implements Unit", "implements Process");
          line = line.replaceFirst("import com.dustedpixels.jasmin.unit.Unit",
              "import com.dustedpixels.jasmin.unit.Process");
          if (methodMatchResult == null) {
            Matcher matcher = Regex.UNIT_UPDATE_END_POINTS_METHOD_PATTERN.matcher(line);
            if (matcher.matches()) {
              methodMatchResult = matcher.toMatchResult();
              methodIndent = methodMatchResult.group(Regex.UNIT_UPDATE_METHOD_INDENT_GROUP);
              writer.write(methodIndent + "public void run(int __cycles) {\n");
              writer.write(methodIndent + "  while (__cycles-- != 0) {\n");
            } else {
              writer.write(line + "\n");
            }
          } else {
            if (Regex.matchesUnitUpdateMethodEnd(methodMatchResult, line)) {
              writer.write(methodIndent + "}\n");
              methodMatchResult = null;
              methodIndent = null;
            } 
            writer.write(line + "\n");
          }
        }
      } while (line != null);
      return writer.toString();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  
  public static void main(String[] args) throws IOException {
    InputStream inputStream = new FileInputStream("src/impl/com/dustedpixels/jasmin/unit/ula/ULA.java");
    try {
      System.out.println(UnitToProcessConverter.convert(IOUtils.toString(inputStream)));
    } finally {
      inputStream.close();
    }
  }
}
